package com.example.demo01.demo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.demo01.R;
import com.example.demo01.consts.MyMediaPlayer;
import com.example.demo01.fragments.TitleFragment;
import com.example.demo01.service.BindService;
import com.example.demo01.service.MyService;
import com.example.demo01.utils.ToastUtil;

public class ServiceDemo extends AppCompatActivity {

    ToastUtil toastUtil = new ToastUtil(this);

    private Button btn_start_play1, btn_start_stop1;

    private Button btn_start_service, btn_start_play2, btn_start_stop2;

    //. 绑定服务
    private BindService bindService;

    //. 绑定服务连接
    private ServiceConnection connection = new ServiceConnection() {
//        参数里有1个IBinder iBinder接口的实例

        //iBinder对象就是service里面onBind方法的返回值
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            BindService.MyBinder myBinder = (BindService.MyBinder) iBinder;
            bindService = myBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //. 添加标题
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fl_title, TitleFragment.newInstance(getResources().getString(R.string.ServiceDemo)))
                .commit();

        initView();
    }

    private void initView() {
        //. 方式一：直接调用 startService() 方法，服务会直接运行。
        btn_start_play1 = findViewById(R.id.btn_start_play1);
        btn_start_stop1 = findViewById(R.id.btn_start_stop1);
        //. 方式二：绑定服务（推荐）
        btn_start_service = findViewById(R.id.btn_start_service);
        btn_start_play2 = findViewById(R.id.btn_start_play2);
        btn_start_stop2 = findViewById(R.id.btn_start_stop2);

        addListener();
    }

    private void addListener() {
        //. 方式一：直接调用 startService() 方法，服务会直接运行。
        btn_start_play1.setOnClickListener(v -> directly(MyMediaPlayer.COMMAND_PLAY));
        btn_start_stop1.setOnClickListener(v -> directly(MyMediaPlayer.COMMAND_PAUSE));

        //. 方式二：绑定服务（推荐）
        btn_start_service.setOnClickListener(v -> bindService(MyMediaPlayer.BIND_SERVICE_COMMAND));
        btn_start_play2.setOnClickListener(v -> bindService(MyMediaPlayer.COMMAND_PLAY));
        btn_start_stop2.setOnClickListener(v -> bindService(MyMediaPlayer.COMMAND_PAUSE));
    }

    //. 直接调用 startService() 方法，服务会直接运行。
    private void directly(String command) {
        Intent intent = new Intent(ServiceDemo.this, MyService.class);
        intent.putExtra(MyMediaPlayer.COMMAND, command);

        startService(intent);

        /*
        [用户点击播放] → 检查系统版本 →
            Android 8.0+ → startForegroundService() →
                服务启动 → 调用 startForeground() →
                    显示通知 → 服务持续运行
            旧版本 → startService() →
                服务启动 → 可能被系统杀死
        * */
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(intent);
//        } else {
//            startService(intent);
//        }
        toastUtil.showToast(command.equals(MyMediaPlayer.COMMAND_PLAY) ? "播放音乐" : "暂停音乐");
    }

    //. 绑定服务式（推荐）
    private void bindService(String command) {

        if (MyMediaPlayer.BIND_SERVICE_COMMAND.equals(command)) {
            //. 绑定服务
            Intent intent = new Intent(ServiceDemo.this, BindService.class);
            boolean b = bindService(intent, connection, Context.BIND_AUTO_CREATE);
            if (b) toastUtil.showToast("绑定服务成功");
        } else if (MyMediaPlayer.COMMAND_PLAY.equals(command)) {
            bindService.play();
            toastUtil.showToast("播放音乐");
        } else if (MyMediaPlayer.COMMAND_PAUSE.equals(command)) {
            bindService.pause();
            toastUtil.showToast("暂停音乐");
        }

    }
}